'use client'

import { Message } from '@/types/chat'
import { useState, useEffect } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'

interface MessageBubbleProps {
  message: Message
  isDarkMode?: boolean
}

// 国际化文本配置
const i18n = {
  zh: {
    uploadedImage: '上传的图片',
    imageLoadFailed: '图片加载失败',
    clickToView: '点击查看文件'
  },
  en: {
    uploadedImage: 'Uploaded image',
    imageLoadFailed: 'Image load failed',
    clickToView: 'Click to view file'
  }
}

export default function MessageBubble({ message, isDarkMode = false }: MessageBubbleProps) {
  const [imageLoaded, setImageLoaded] = useState<{[key: string]: boolean}>({})
  const [language, setLanguage] = useState<'zh' | 'en'>('zh')
  const isUser = message.role === 'user'

  // 检测系统语言
  useEffect(() => {
    const detectLanguage = () => {
      const userLang = navigator.language || (navigator as any).userLanguage
      const isZh = userLang.toLowerCase().startsWith('zh')
      setLanguage(isZh ? 'zh' : 'en')
    }
    detectLanguage()
  }, [])

  const t = i18n[language]

  // 处理消息内容
  const renderContent = () => {
    if (typeof message.content === 'string') {
      return (
        <div className={`prose prose-sm max-w-none ${isDarkMode ? 'prose-invert' : 'prose-gray'}`}>
          <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]}>
            {message.content}
          </ReactMarkdown>
        </div>
      )
    }

    return (
      <div className="space-y-3">
        {message.content.map((item, index) => {
          switch (item.type) {
            case 'text':
              return (
                <div key={index} className={`prose prose-sm max-w-none ${isDarkMode ? 'prose-invert' : 'prose-gray'}`}>
                  <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]}>
                    {item.text || ''}
                  </ReactMarkdown>
                </div>
              )

            case 'image_url':
              return (
                <div key={index} className="mt-2">
                  <img
                    src={item.image_url?.url}
                    alt={t.uploadedImage}
                    className="max-w-full h-auto rounded-lg cursor-pointer hover:opacity-90 transition-opacity"
                    onClick={() => window.open(item.image_url?.url, '_blank')}
                    onLoad={() => setImageLoaded(prev => ({ ...prev, [item.image_url?.url || '']: true }))}
                    onError={() => setImageLoaded(prev => ({ ...prev, [item.image_url?.url || '']: false }))}
                  />
                  {!imageLoaded[item.image_url?.url || ''] && (
                    <div className={`w-full h-32 ${isDarkMode ? 'bg-gray-700' : 'bg-gray-200'} rounded-lg flex items-center justify-center`}>
                      <div className={isDarkMode ? 'text-gray-400' : 'text-gray-500'}>{t.imageLoadFailed}</div>
                    </div>
                  )}
                </div>
              )

            case 'file_url':
              return (
                <div key={index} className="mt-2">
                  <div className={`flex items-center p-3 ${isDarkMode ? 'bg-gray-700 hover:bg-gray-600' : 'bg-gray-100 hover:bg-gray-200'} rounded-lg transition-colors cursor-pointer`}
                       onClick={() => window.open(item.url, '_blank')}>
                    <div className="mr-3">
                      <svg className={`w-6 h-6 ${isDarkMode ? 'text-gray-400' : 'text-gray-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                      </svg>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className={`text-sm font-medium ${isDarkMode ? 'text-gray-200' : 'text-gray-900'} truncate`}>
                        {item.name}
                      </p>
                      <p className={`text-sm ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
                        {t.clickToView}
                      </p>
                    </div>
                    <div className="ml-3">
                      <svg className={`w-4 h-4 ${isDarkMode ? 'text-gray-500' : 'text-gray-400'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                      </svg>
                    </div>
                  </div>
                </div>
              )

            default:
              return null
          }
        })}
      </div>
    )
  }

  return (
    <div className={`flex ${isUser ? 'justify-end' : 'justify-start'}`}>
      <div className={`max-w-[85%] sm:max-w-xs lg:max-w-md ${
        isUser
          ? `px-3 py-2 sm:px-4 sm:py-2 rounded-2xl ${isDarkMode ? 'bg-blue-600 text-white' : 'bg-black text-white'}`
          : message.isError
            ? `px-3 py-2 sm:px-4 sm:py-2 rounded-2xl ${isDarkMode ? 'bg-red-900 text-red-200 border border-red-700' : 'bg-red-100 text-red-800 border border-red-200'}`
            : 'px-0 py-1'  // AI消息无背景、无边框、无阴影
      }`}>
        {/* 头像和时间 - 只对用户消息显示 */}
        {isUser && (
          <div className="flex items-center mb-1 justify-end">
            <span className={`text-xs ${isDarkMode ? 'text-blue-200' : 'text-gray-300'}`}>
              {message.timestamp.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
              })}
            </span>
          </div>
        )}

        {/* 消息内容 */}
        <div className={`text-sm leading-relaxed ${message.isError ? 'font-medium' : ''}`}>
          {renderContent()}
        </div>

        {/* AI消息的时间戳 - 在内容下方 */}
        {!isUser && !message.isError && (
          <div className="flex items-center mt-1 justify-start">
            <span className={`text-xs ${isDarkMode ? 'text-gray-500' : 'text-gray-500'}`}>
              {message.timestamp.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
              })}
            </span>
          </div>
        )}
      </div>
    </div>
  )
}
